/*
 * Copyright (c) 2007-2011, Petr Panteleyev
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *    3. The name of the author may not be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.panteleyev.blogclient;

import java.lang.reflect.InvocationTargetException;
import java.net.CookieHandler;
import java.util.logging.Level;

import javax.script.ScriptException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.jdesktop.swingx.JXErrorPane;
import org.jdesktop.swingx.error.ErrorInfo;

import org.panteleyev.flickrapi.FlickrAccount;
import org.panteleyev.flickrapi.FlickrException;
import org.panteleyev.flickrapi.FlickrResponseException;
import org.panteleyev.fotobilder.FotoBilderException;
import org.panteleyev.gclient.GBCommentsNotEnabledException;
import org.panteleyev.gclient.GBException;
import org.panteleyev.html.HTMLEditorException;
import org.panteleyev.ljapi.LJJournalException;
import org.panteleyev.swing.OSUtil;
import org.panteleyev.swing.WindowManager;
import org.panteleyev.swing.WindowManagerListener;

public class MainClass{
    private static String vendors[] = {
        "Sun Microsystems", "Oracle"
    };
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        if (!checkVM()) {
            JOptionPane.showMessageDialog(null, System.getProperty("java.vm.name") +
                    " made by " + System.getProperty("java.vm.vendor") +
                    " is not supported.\nPlease get JRE 1.7+ made by Sun Microsystems Inc.", "Error", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }

        WindowManager.setListener(new WindowManagerListener() {
            @Override
            public void allFramesHidden() {
                Options.storeSettings();
                System.exit(0);
            }
        });

        // Workaround for JWS
        // http://forums.sun.com/thread.jspa?threadID=744166
        CookieHandler.setDefault(null);

        Options.loadSettings();
        Options.setLocale();
        Options.setSystemProxySettings();

        FlickrAccount.setAPIKeys(Options.FLICKR_API_KEY, Options.FLICKR_API_SECRET);

        templateManager = new TemplateManager();
        templateManager.load();

        UserProfileManager.loadProfiles();


        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                if (!OSUtil.isMacOSX()) {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        // just ingore
                    }
                }
                UserProfileListFrame f = new UserProfileListFrame();

                if (Options.getShowProfileManager() || UserProfileManager.getProfileCount() == 0) {
                    f.setVisible(true);
                } else {
                    f.onConnect();
                }
            }
        });
    }

    private static boolean checkVM() {
        if (OSUtil.isMacOSX()) {
            return true;
        } else {
            String vendor = System.getProperty("java.vm.vendor");
            if (vendor != null) {
                for (String v : vendors) {
                    if (vendor.indexOf(v) != -1) {
                        return true;
                    }
                }
            }

            return false;
        }
    }

    public static void handleException(final JFrame frame, final Throwable e) {
        String msg = e.getMessage();
        Level lvl = Level.SEVERE;

        if (e instanceof InvocationTargetException) {
            Throwable tE = ((InvocationTargetException)e).getTargetException();
            msg += "\n Target: " + tE.toString();
            msg += "\n Message: " + tE.getMessage();

            StackTraceElement[] stackTrace = e.getStackTrace();
            for (StackTraceElement st : stackTrace) {
                msg += "\n" + st.toString();
            }
        }

        String title = e.toString();

        if (e instanceof HTMLEditorException) {
            title = "HTML Editor Exception";
            msg = e.getCause().getMessage();
        }

        if (e instanceof ScriptException) {
            title = "Script Error";
            ScriptException se = (ScriptException)e;
            msg = "Error at line " + se.getLineNumber() + "\n" + se.getMessage();
            lvl = Level.WARNING;
        }

        if (e instanceof FlickrResponseException) {
            title = "Flickr Error";
            FlickrResponseException fe = (FlickrResponseException)e;
            msg = fe.getCode() + ": " + fe.getMessage();
        }

        if (e instanceof LJJournalException) {
            title = "Journal Error";
        } else {
            if (e instanceof GBCommentsNotEnabledException) {
                title = "blogger.com Error";
                msg = "Comments are not enabled for this post";
            } else {
                if (e instanceof GBException) {
                    title = "blogger.com Error";
                } else {
                    if (e instanceof FotoBilderException) {
                        title = "FotoBilder exception";
                    } else {
                        if (e instanceof java.io.IOException) {
                            title = "Input/Output Exception";
                        } else {
                            if (e instanceof java.net.MalformedURLException) {
                                title = "Bad URL";
                            } else {
                                if (e instanceof FlickrException) {
                                    title = "Flickr Error";
                                }
                            }
                        }
                    }
                }
            }
        }

        final String m = msg;
        final String t = title;
        final Level l = lvl;

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JXErrorPane.showDialog(frame, new ErrorInfo(t, m, null, null,  e, l, null));
            }
        });
    }

    public static boolean showConfirmDialog(JFrame frame) {
        return JOptionPane.showConfirmDialog(
                frame,
                L10N.CONFIRM_DIALOG_MESSAGE.s(),
                L10N.CONFIRM_DIALOG_TITLE.s(),
                JOptionPane.YES_NO_OPTION
                ) == JOptionPane.YES_OPTION;
    }

    public static TemplateManager getTemplateManager() {
        return templateManager;
    }

    /* List of supported servers */
    private static TemplateManager             templateManager;
}
